package es.usj.apps.moviles.parsers;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Iterator;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.util.Log;

public class ParserJSON {

	public interface OnParserJSONListener {
		public void onParserJSONResult(WsResult<?> result);
	}

	OnParserJSONListener mListener = null;

	public void setOnParserJSONListener(OnParserJSONListener listener) {
		mListener = listener;
	}

	private static String convertStreamToString(InputStream is) {
		/*
		 * To convert the InputStream to String we use the
		 * BufferedReader.readLine() method. We iterate until the BufferedReader
		 * return null which means there's no more data to read. Each line will
		 * appended to a StringBuilder and returned as String.
		 */
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		StringBuilder sb = new StringBuilder();

		String line = null;
		try {
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return sb.toString();
	}
	
	private WsResult<?> connect(String url) {

		HttpClient httpclient = new DefaultHttpClient();

		// Prepare a request object
		HttpGet httpget = new HttpGet(url);

		// Execute the request
		HttpResponse response;
		try {
			
			response = httpclient.execute(httpget);
			// Examine the response status
			Log.i("Electric-Vehicle", response.getStatusLine().toString());

			// Get hold of the response entity
			HttpEntity entity = response.getEntity();
			// If the response does not enclose an entity, there is no need
			// to worry about connection release

			if (entity != null) {

				// A Simple JSON Response Read
				InputStream instream = entity.getContent();
				String result = convertStreamToString(instream);
				//Log.i("Electric-Vehicle", result);

				// A Simple JSONObject Creation
				JSONArray json = new JSONArray(result);
				//Log.i("Electric-Vehicle", json.toString());

				WsResult<HashMap<?, ?>> res = new WsResult<HashMap<?, ?>>();
	
				for (int i = 0; i < json.length(); i++) {

					JSONObject obj = json.getJSONObject(i);
					//Log.d("Electric-Vehicle", obj.toString());

					HashMap<String,String> item = new HashMap<String,String>();
				    Iterator<?> iter = obj.keys();
				    
				    while(iter.hasNext()) {
				    	
				        String key = (String)iter.next();
				        String value = obj.getString(key);
				        item.put(key,value);
				    }
	
					res.addObject(item);
				}

				// Closing the input stream will trigger connection release
				instream.close();

				return res;
			}

		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		}

		return null;
	}

	public void startConnection(String url) {

		Log.i("Electric-vehicle", url);
		new ConnectionAsync().execute(url);
	}

	private class ConnectionAsync extends AsyncTask<String, Void, WsResult<?>> {

		@Override
		protected void onPreExecute() {

			super.onPreExecute();
		}

		@Override
		protected WsResult<?> doInBackground(String... arg0) {

			WsResult<?> result = null;

			if (arg0.length > 0) {
				String url = arg0[0];
				result = connect(url);
			}

			return result;
		}

		@Override
		protected void onPostExecute(WsResult<?> result) {
			if (mListener != null) {
				mListener.onParserJSONResult(result);
			}
		}
	}
}
